package cn.picclife.mwx.manager.sys.controller;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.picclife.mwx.manager.sys.model.bo.DataCollectBo;
import cn.picclife.mwx.manager.sys.model.bo.DataCollectResponse;
import cn.picclife.mwx.manager.sys.model.bo.DataResponse;
import cn.picclife.mwx.manager.sys.model.bo.PageCount;
import cn.picclife.mwx.manager.sys.model.bo.PageResponse;
import cn.picclife.mwx.manager.sys.model.bo.UpdateCollectReq;
import cn.picclife.mwx.manager.sys.model.po.Archive;
import cn.picclife.mwx.manager.sys.model.po.SysMaintain;
import cn.picclife.mwx.manager.sys.service.QualityDataService;
import cn.picclife.mwx.manager.util.enums.ResponseStatusEnum;
@RequestMapping("quality")
@RestController
public class QualityDataController {
	
	@Autowired
	private QualityDataService  QualityServiceImpl;
	private Log log = LogFactory.getLog(QualityDataController.class);

	/**
	 * 质检审核列表查询
	 * @param req 
	 * @return
	 */
	@RequestMapping(value="/queryDataList", method= {RequestMethod.POST})
	public PageResponse queryDataList(@RequestBody UpdateCollectReq req) {

		log.info("===========queryList查询接口请求报文："+JSONObject.toJSON(req).toString());
		PageResponse pageResponse = new PageResponse();
		PageCount pageCount = new PageCount();
		try {
			pageCount = QualityServiceImpl.queryDataList(req);
		} catch (Exception e) {
			log.error(e);
			pageResponse.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			pageResponse.setMsg(ResponseStatusEnum.EXCEPTION.getName());
			log.info("===========queryList质检审核列表查询接口返回报文："+JSONObject.toJSON(pageResponse).toString());
			return pageResponse;
		}
		pageResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		pageResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		pageResponse.setPageCount(pageCount);
		log.info("===========queryList质检审核列表查询接口返回成功=========");
		return pageResponse;
	}
	
	@RequestMapping(value="/queryDataFile", method= {RequestMethod.POST})
	public DataCollectResponse queryDataFile(@RequestBody UpdateCollectReq req,HttpServletRequest request) {
		
		log.info("===========queryDataFile视频回放接口请求报文："+JSONObject.toJSON(req).toString());
		DataCollectResponse dataResponse = new DataCollectResponse();
		if(null==req||null==req.getId()||req.getId().trim().length()<=0) {
			dataResponse.setCode(ResponseStatusEnum.PARAM_IS_NULL.getCode());
			dataResponse.setMsg(ResponseStatusEnum.PARAM_IS_NULL.getName());
			log.info("===========queryDataFile视频回放接口返回报文："+JSONObject.toJSON(dataResponse).toString());
			return dataResponse;
		}
		List strList = new ArrayList<String>();
		List userList = null;
		try {
			//查询播放数据信息
			strList = QualityServiceImpl.queryDataFile(req);
			//查询播放人员历史信息
			userList =  QualityServiceImpl.queryUserList(req.getId(), request);
		} catch (Exception e) {
			log.error(e);
			dataResponse.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			dataResponse.setMsg(ResponseStatusEnum.EXCEPTION.getName());
			log.info("===========queryDataFile视频回放接口返回报文："+JSONObject.toJSON(dataResponse).toString());
			return dataResponse;
		}
		if(null==strList) {
			dataResponse.setCode(ResponseStatusEnum.NOT_DATA.getCode());
			dataResponse.setMsg(ResponseStatusEnum.NOT_DATA.getName());
			log.info("===========queryDataFile视频回放接口返回报文："+JSONObject.toJSON(dataResponse).toString());
			return dataResponse;
		}
		dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		dataResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		dataResponse.setData(strList);
		dataResponse.setUserList(userList);
		log.info("===========queryDataFile视频回放接口返回成功：id="+req.getId());
		return dataResponse;
	}
	
	/**
	 * 数据更新接口
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/updateCollect", method= {RequestMethod.POST})
	public DataResponse updateCollect(@RequestBody UpdateCollectReq req) {
		
		int updateFlag = 0;
		log.info("===========updateCollect数据更新接口请求报文："+JSONObject.toJSON(req).toString());
		DataResponse dataResponse = new DataResponse();
		if(null==req||null==req.getId()||req.getId().trim().length()<=0) {
			dataResponse.setCode(ResponseStatusEnum.PARAM_IS_NULL.getCode());
			dataResponse.setMsg(ResponseStatusEnum.PARAM_IS_NULL.getName());
			log.info("===========updateCollect数据更新接口返回报文："+JSONObject.toJSON(dataResponse).toString());
			return dataResponse;
		}
		try {
			updateFlag = QualityServiceImpl.updateData(req);
			
		} catch (Exception e) {
			log.error(e);
			dataResponse.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			dataResponse.setMsg(ResponseStatusEnum.EXCEPTION.getName());
			log.info("===========updateCollect数据更新接口返回报文："+JSONObject.toJSON(dataResponse).toString());
			return dataResponse;
		}
		if(updateFlag==0) {
			dataResponse.setCode(ResponseStatusEnum.NOT_DATA.getCode());
			dataResponse.setMsg(ResponseStatusEnum.NOT_DATA.getName());
			log.info("===========updateCollect数据更新接口返回报文："+JSONObject.toJSON(dataResponse).toString());
			return dataResponse;
		}
		dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		dataResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		log.info("===========updateCollect数据更新接口返回报文："+JSONObject.toJSON(dataResponse).toString());
		return dataResponse;
	}
	
	
	
	@RequestMapping(value="/queryAccountList", method= {RequestMethod.POST})
	public PageResponse queryAccountList(@RequestBody DataCollectBo bo,HttpServletRequest request) {
		log.info("===========queryAccountList查询接口请求报文："+JSONObject.toJSON(bo).toString());	
		PageResponse pageResponse = new PageResponse();
		PageCount pageCount = new PageCount();
		try {
			pageCount =QualityServiceImpl.queryAccountList(bo,request);
		} catch (Exception e) {
			log.error(e);
			pageResponse.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			pageResponse.setMsg(ResponseStatusEnum.EXCEPTION.getName());
			log.info("===========queryAccountList查询接口返回报文："+JSONObject.toJSON(pageResponse).toString());
			return pageResponse;
		}
		pageResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		pageResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		pageResponse.setPageCount(pageCount);
		log.info("===========queryAccountList查询接口返回成功=========");
		return pageResponse;
		
		
	}
	
	@RequestMapping(value="/querySysMaintain", method= {RequestMethod.POST})
	public DataResponse querySysMaintain(@RequestBody SysMaintain maintain,HttpServletRequest request) {
		
		List<SysMaintain> list = new ArrayList<>();
		log.info("===========querySysMaintain数据更新接口请求报文："+JSONObject.toJSON(maintain).toString());
		DataResponse dataResponse = new DataResponse();
		
		try {
			 list = QualityServiceImpl.querySysMaintain(maintain,request);
			 dataResponse.setData(list);
		} catch (Exception e) {
			log.error(e);
			dataResponse.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			dataResponse.setMsg(ResponseStatusEnum.EXCEPTION.getName());
			log.info("===========querySysMaintain数据更新接口返回报文："+JSONObject.toJSON(dataResponse).toString());
			return dataResponse;
		}		
		dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		dataResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		log.info("===========querySysMaintain数据更新接口返回报文："+JSONObject.toJSON(dataResponse).toString());
		return dataResponse;
	}

	/**
	 * 获取磁盘可用空间
	 * @param archive
	 * @return
	 */
	@RequestMapping(value="/querySpace", method= {RequestMethod.POST})
	public DataResponse querySpace(@RequestBody Archive archive) {
		log.info("querySpace获取磁盘可用空间请求报文："+archive);
		DataResponse dataResponse = new DataResponse();		
		try {      
			
			String disk = archive.getArchiveDir();
			log.info("disk:"+disk);
			if(disk.equals("/root")) {
				List list = new ArrayList<>();
				log.info("=====进入root=====");
				File diskPartition = new File(disk); 		 
				long usableSpace = diskPartition.getUsableSpace(); //可用剩余空间，单位为M 			
				usableSpace = usableSpace/1024/1024/1024;
				log.info("usableSpace:"+usableSpace);
				long total = diskPartition.getTotalSpace();		
				total = total/1024/1024/1024;
				log.info("total:"+total);
				long free=diskPartition.getFreeSpace();
				free=free/1024/1024/1024;
				log.info("free:"+free);
				if(0==total) {
					dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
					dataResponse.setMsg("该磁盘不存在");
					return dataResponse;
				}else {
					double use = usableSpace/(double)total;
					Map<String,Object> map= new HashMap<>();
                    map.put("disk", disk);
                    map.put("value", Integer.parseInt(new DecimalFormat("0").format(use*100))+"%");
					list.add(map);
				}		
				dataResponse.setData(list);
			}else {
				List list = new ArrayList<>();
				log.info("=====进入dev======");
				Runtime rt = Runtime.getRuntime();
	            Process p = rt.exec("df -hl");// df -hl 查看硬盘空间
	            List<String> result = IOUtils.readLines(p.getInputStream(), "GBK");
	            for (String line: result) {    
	            	log.info("line1:"+line);
	            	String deskName= archive.getArchiveDir();  
	            	log.info("deskName:"+deskName);
	                if (line.contains(deskName)) {
	                	log.info("line2:"+line);
	                    String[] items = line.split("%")[0].split(" ");
	                    int lastIndex = items.length - 1;
	                    double useRateLocal = Double.parseDouble(items[lastIndex].trim());
	                    log.info("===>>>"+"磁盘名称："+deskName+"磁盘使用率："+useRateLocal);
	                    Map<String,Object> map= new HashMap<>();
	                    map.put("disk", line.substring(0,line.indexOf(" ")));
	                    map.put("value", 100-useRateLocal+"%");
	                    list.add(map);
	                }
	            } 
	            if(list.size()==0) {
	            	dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
					dataResponse.setMsg("该磁盘不存在");
					return dataResponse;
	            }
	            dataResponse.setData(list);
			}
			
		} catch (Exception e) {
			log.error(e);
			dataResponse.setCode(ResponseStatusEnum.EXCEPTION.getCode());
			dataResponse.setMsg(ResponseStatusEnum.EXCEPTION.getName());
			log.info("===========querySpace获取磁盘可用空间接口返回报文："+JSONObject.toJSON(dataResponse).toString());
			return dataResponse;
		}		
		dataResponse.setCode(ResponseStatusEnum.SUCCESS_CODE.getCode());
		dataResponse.setMsg(ResponseStatusEnum.SUCCESS_CODE.getName());
		log.info("===========querySpace获取磁盘可用空间接口返回报文："+JSONObject.toJSON(dataResponse).toString());
		return dataResponse;
	}

}
